//
//  BIDBindingHouseViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/19.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDBindingHouseViewController.h"
#import "BIDHousePickerView.h"
#import <SMS_SDK/SMSSDK.h>

//检查输入的手机号与业主预留的手机号是否相同
static NSString *checkPhoneIsHouseHolderURL = @"memberHouseAndroid/checkHouseHolder.action";

//获取小区所有房屋分布
static NSString *allHouseListURL = @"client/repair/gainHouseList.action";

//绑定房产
static NSString *bindingHouseURL = @"memberHouseAndroid/add.action";

@interface BIDBindingHouseViewController ()<BIDHousePickerViewDelegate>
{
    NSTimer *_timer;
    NSUInteger _totalSecond;
    NSMutableArray *_allHouseArr;
    BIDHousePickerView *_housePickerView;
    //业主预留的手机号
    NSString *_phoneNumberForVerify;
    //
    NSString *_houseName;
    NSString *_houseCode;
}
@end

@implementation BIDBindingHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"绑定房产";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeHandler)];
    //
    _phoneTF.inputAccessoryView = self.toolBar;
    _verifyCodeTF.inputAccessoryView = self.toolBar;
    //
    [_verifyCodeBtn setTitleColor:RGBACOLOR(27.f, 193.f, 166.f, 1.f) forState:UIControlStateNormal];
    [_verifyCodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
    //
    _totalSecond = 60;
    _allHouseArr = [NSMutableArray array];
    _houseCode = @"";
    [self fetchAllHouse];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)closeHandler
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

/**
 获取小区所有房屋分布
 */
- (void)fetchAllHouse
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], allHouseListURL];
    NSString *strPost = @"";
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(!errMsg)
        {
            NSArray *arr = (NSArray *)responseDic;
            _allHouseArr = [[NSMutableArray alloc] initWithArray:arr];
            //
            _housePickerView = [[BIDHousePickerView alloc] initWithMenuArr:_allHouseArr];
            _housePickerView.bIsInputView = YES;
            _housePickerView.delegate = self;
            _houseCodeTF.inputView = _housePickerView;
        }
    }];
}

- (void)timerFireMethod:(NSTimer*)timer
{
    _totalSecond--;
    if(_totalSecond==0)
    {
        _totalSecond = 60;
        [_timer invalidate];
        [_verifyCodeBtn setEnabled:YES];
        [_verifyCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    else
    {
        NSString *str = [[NSString alloc] initWithFormat:@"%ld秒后可重新获取", (long)_totalSecond];
        [_verifyCodeBtn setTitle:str forState:UIControlStateDisabled];
    }
}

/**
 获取验证码
 
 @param sender <#sender description#>
 */
- (IBAction)verifyCodeBtnHandler:(id)sender
{
    [_phoneTF resignFirstResponder];
    _phoneNumberForVerify = _phoneTF.text;
    _phoneNumberForVerify = _phoneTF.text;
    if(_phoneNumberForVerify.length > 0)
    {
        //验证手机号格式是否正确
        BOOL isCorrect = [BIDGlobalMethods isMobilePhoneNumberHaveCorrectFormat:_phoneNumberForVerify];
        if(isCorrect)
        {
            //验证手机号是否是房屋业主预留的手机号
            NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], checkPhoneIsHouseHolderURL];
            NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&memberHouse.telephone=%@&memberHouse.houseCode=%@", [AppDelegate getUserId], _phoneNumberForVerify, _houseCode];
            self.bManualHandleHTTPFailed = YES;
            [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
                if(errMsg)
                {
                    [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                }
                else
                {
                    //发送手机验证码
                    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneNumberForVerify zone:@"86" customIdentifier:nil result:^(NSError *error){
                        if(!error)
                        {
                            [_verifyCodeBtn setEnabled:NO];
                            _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
                            [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                            [self showHint:@"验证码已发送"];
                        }
                        else
                        {
                            NSString *strError = [[NSString alloc] initWithFormat:@"%@", error];
                            [self showAlertView:strError buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                        }
                    }];
                }
            }];
        }
        else
        {
            [self showAlertView:@"请输入有效的手机号码" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
    else
    {
        [self showAlertView:@"请填写手机号码" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
    }
}

/**
 绑定房产
 */
- (IBAction)bindingHouseBtnHandler:(id)sender
{
    NSString *strVerifyCode = _verifyCodeTF.text;
    if(strVerifyCode.length == 0)
    {
        [self showAlertView:@"请输入短信验证码" buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
        return;
    }
    [SMSSDK commitVerificationCode:strVerifyCode phoneNumber:_phoneNumberForVerify zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error){
        if(!error)
        {
            //短信验证码验证通过,执行绑定房产操作
            [self bindingHouse];
        }
        else
        {
            NSString *strError = [[NSString alloc] initWithFormat:@"%@", error];
            [self showAlertView:strError buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }];
}

- (void)bindingHouse
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], bindingHouseURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&memberHouse.houseCode=%@&memberHouse.address=%@&memberHouse.telephone=%@&memberHouse.ownerPhone=%@", [AppDelegate getUserId], _houseCode, _houseName, [AppDelegate getUserName], _phoneNumberForVerify];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id obj, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if([obj isKindOfClass:[NSArray class]])
            {
                NSArray *arr = (NSArray *)obj;
                [AppDelegate setBindingHouse:arr];
            }
            [self showAlertView:@"绑定成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
        }
    }];
}

- (void)alertViewHandler:(id)obj
{
    
     [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - BIDHousePickerViewDelegate
- (void)chooseHouseName:(NSString *)houseName houseCode:(NSString *)houseCode
{
    _houseCode = houseCode;
    _houseName = houseName;
    _houseCodeTF.text = houseName;
}

@end
